package iot

import (
	"errors"
	"gorm.io/gorm"
	"iot-base/common/eventtype"
)

type (
	Event     eventtype.Event
	EventMode struct {
		db *gorm.DB
	}
)

func NewEventMode(db *gorm.DB) *EventMode {
	return &EventMode{
		db,
	}
}

func (m *EventMode) FindCount(thingId, stationsId string) (int64, error) {
	var total int64
	dbSession := m.db.Model(&Event{})
	if thingId != "" {
		dbSession.Where("t_id = ?", thingId)
	}
	if stationsId != "" {
		dbSession.Where("station_id = ?", stationsId)
	}
	err := dbSession.Count(&total).Error
	return total, err
}

func (m *EventMode) FindList(thingId, stationsId string, page, size int) ([]Event, error) {
	var result []Event
	dbSession := m.db.Model(&Event{})
	if thingId != "" {
		dbSession.Where("t_id = ?", thingId)
	}
	if stationsId != "" {
		dbSession.Where("station_id = ?", stationsId)
	}
	dbSession.Order("time desc").Limit(size).Offset((page - 1) * size)
	err := dbSession.Find(&result).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return []Event{}, nil
	}
	return append([]Event{}, result...), err
}
